import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.SQLOutput;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ASUS
 * Date: 2023-08-16
 * Time: 13:37
 */
public class JDBCInsert {
    public static void main(String[] args) throws SQLException {

        Scanner scan = new Scanner(System.in);

        //JDBC需要通过以下步骤完成开发
        //1.创建并初始化一个数据源
        DataSource datasource = new MysqlDataSource();
        ((MysqlDataSource)datasource).setUrl("jdbc:mysql://127.0.0.1:3306/java107?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)datasource).setUser("root");
        ((MysqlDataSource)datasource).setPassword("111111");
        //2.与服务器建立连接
        Connection connection =datasource.getConnection();
        //3.从控制台读取用户输入的信息
        System.out.println("请输入学生姓名：");
        String name = scan.next();
        System.out.println("请输入学号id:");
        int id = scan.nextInt();
        //4.构造sql语句
        String sql = "insert into student value(?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);
        System.out.println(statement);
        //5.执行sql语句
        int ret = statement.executeUpdate();
        System.out.println("ret = "+ret);
        //6.释放必要的资源
        statement.close();
        connection.close();

    }
}
